package cn.blu10ph.trustshare.schedule;

import cn.blu10ph.trustshare.bean.node.TrustNode;
import cn.blu10ph.trustshare.constant.Constant;
import cn.blu10ph.trustshare.core.ServiceCore;
import cn.blu10ph.trustshare.service.DHTMsgService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * <p> PingSend </p >
 *
 * @author cxx
 * @date 2024/4/1 21:31
 */
@Slf4j
@Component
public class PingSend {

    @Resource
    ServiceCore serviceCore;

    @Scheduled(fixedDelay = Constant.PING_TIME, initialDelay = 10 * 1000)
    public void doJob() {
        DHTMsgService<Object> pingMsgService = serviceCore.getMsgService(Constant.MSG_TYPE_PING);
        long nowTime = System.currentTimeMillis();
        Long pingTime = nowTime - Constant.PING_TIME;
        List<TrustNode> nodes = serviceCore.getAllNodeList();
        for(TrustNode node : nodes){
            Long activeTime = serviceCore.getNodeActive(node.getNodeId());
            // if node is not active
            if (ObjectUtils.isEmpty(activeTime) || pingTime.compareTo(activeTime)>0) {
                try {
                    pingMsgService.sendQuery(node, null);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

}
